package com.itcast.demo;

import cn.itcast.dao.UsersDao;
import cn.itcast.domain.Params;
import cn.itcast.domain.Users;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * @author zhangzhuang@123456
 * @DATE 2018/11/7
 * @TIME 11:08
 */
public class Demo {
    private  InputStream is;
    private  SqlSession session;
    private  UsersDao dao;

    @Before
    public void init() throws Exception {
        //1.读取核心配置文件
        is = Resources.getResourceAsStream("SqlConfig.xml");
        //2.创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        //3.获取session对象
        session = factory.openSession();
        //4.获取Mapper对象
        dao = session.getMapper(UsersDao.class);
    }

    @After
    public void destory() throws IOException {
        session.commit();
        session.close();
        is.close();
    }

    /**
     * 查询所有
     */
    @Test
    public void findAll(){
        List<Users> list = dao.findAll();
        for (Users users : list) {

            System.out.println(users);
        }
    }

    /**
     * 添加用户
     */
    @Test
    public void addUsers(){
        Users u = new Users();

        u.setUsername("李四");
        u.setSex("男");
        u.setAddress("合肥");
        u.setBirthday(new Date());

        dao.addUsers(u);
    }

    /**
     * 修改
     */
    @Test
    public void updateUser(){
        Users u = new Users();

        u.setId(50);
        u.setUsername("李四");
        u.setSex("男");
        u.setAddress("上海");
        u.setBirthday(new Date());

        dao.updateUser(u);
    }

    /**
     * 删除
     */
    @Test
    public void deleteUser(){
        dao.deleteUser(50);
    }

    /**
     * 模糊查询
     */
    @Test
    public void findLike(){
        List<Users> list = dao.findLike("%王%");
        for (Users users : list) {
            System.out.println(users);
        }
    }

    /**
     * 查询所有
     */
    @Test
    public void getNum(){
        int i = dao.cnum();
        System.out.println(i);
    }

    /**
     * 查询一个
     */
    @Test
    public void findOne(){
        Params params = new Params();
        Users users = new Users();
        users.setUsername("李四");
        params.setUsers(users);

        List<Users> list = dao.findOne(params);
        System.out.println(list);
    }
}
